package org.phmanago.gui;

import java.awt.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

import java.awt.event.*;
import java.util.Iterator;

import org.phmanago.core.*;

public class StructurePanel extends JPanel implements TreeSelectionListener {
	
	private Album dataModel = null;
	private JTree localTree;
	
	public StructurePanel () {
	
	}
	
	public StructurePanel(Album dm) {
		dataModel = dm;
		initComponents();
	}
	
	public void setModel(Album dm) {
		dataModel = dm;
		initComponents();
	}
	
	public void initComponents() {
        setLayout(new FlowLayout());
        localTree = createTree();
        localTree.addTreeSelectionListener(this);
        JScrollPane treeView = new JScrollPane(localTree);
        treeView.setPreferredSize(new Dimension(200,440));
        add(treeView);
        setVisible(true);
        
	}
	
	private JTree createTree() {
		if (dataModel == null)
			throw new NullPointerException();
		
		DefaultMutableTreeNode parent = null;
	    DefaultMutableTreeNode child = null;
		DefaultMutableTreeNode top = new DefaultMutableTreeNode(dataModel.getName());
		
		Iterator it = dataModel.getNodes();
		while (it.hasNext()) {
			Node n = (Node)it.next();
			
			parent = new DefaultMutableTreeNode(n);

			top.add(parent);
			
			Iterator it2 = n.getIterator();
			while (it2.hasNext()) {
				Attribute at = (Attribute)it2.next();
				
				child = new DefaultMutableTreeNode(at);

				parent.add(child);
			}
		}
		
		return new JTree(top);
	}
	
	public void addTreeSelectionListener(TreeSelectionListener tsl) {
		localTree.addTreeSelectionListener(tsl);
	}
	
	public void valueChanged(TreeSelectionEvent e) {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) localTree.getLastSelectedPathComponent();

		if (node == null)
			return;

		Object nodeInfo = node.getUserObject();
		if (nodeInfo instanceof Node)
			System.out.println("Node clicked: " + (Node)nodeInfo);
		else if (nodeInfo instanceof Attribute) 
			System.out.println("Node clicked: " + (Attribute)nodeInfo);

	}
}
